package fr.sedoo.rbv.geonetwork.request;

import java.io.InputStream;
import java.io.StringWriter;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.io.IOUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;

import fr.sedoo.rbv.geonetwork.config.GeonetworkConfig;
import fr.sedoo.rbv.geonetwork.domain.GeonetworkUser;

public class MetadataExistRequest extends AuthenticatedRequest 
{

	String id="";

	public MetadataExistRequest(String id, GeonetworkConfig config)
	{
		super(config);
		this.id = id;

	}

	public MetadataExistRequest(String id, GeonetworkUser user)
	{
		super(user);
		this.id = id;

	}

	public MetadataExistRequest(String id)
	{
		super();
		this.id = id;

	}

	public boolean execute() throws Exception
	{

		/*
		 * On utilise une requete CSW avec un outputschema par défaut et un ElementSetName de type brief, afin de ne ramener que les informations minimales 
		 */

		Namespace csw = Namespace.getNamespace("csw", "http://www.opengis.net/cat/csw/2.0.2");
		Element request = new Element("GetRecordById",csw); 
		//request.setAttribute("outputSchema","csw:IsoRecord").setAttribute("service", "CSW").setAttribute("version", "2.0.2");
		request.setAttribute("service", "CSW").setAttribute("version", "2.0.2");
		request.addContent(new Element("Id",csw).setText(id));
		request.addContent(new Element("ElementSetName",csw).setText("brief"));

		String cswURL = getConfig().getCSWURL();
		PostMethod post = new PostMethod(cswURL);

		try {
			String postData = getString(new Document(request));
			post.setRequestEntity(new StringRequestEntity(postData,"application/xml", "UTF8"));
			String rawXml = executePostMethod(post);
			if (rawXml.indexOf(id)>0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		catch (Exception e)
		{	
			throw new Exception(e);
		}
		finally {
			post.releaseConnection();
		}
	}

}
